﻿using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using UnityEngine.UI;
using System.Linq;
using UnityEditor.SceneManagement;

public class TextEditorWindow : EditorWindow
{
    private List<Text> textComponents = new List<Text>();
    private List<UILabel> uiLabelComponents = new List<UILabel>();
    private Dictionary<string, List<MonoBehaviour>> uniqueTexts = new Dictionary<string, List<MonoBehaviour>>();
    private string selectedText = "";
    private string newText = "";
    private int selectedIndex = -1; // 添加这个变量来跟踪选中的索引

    [MenuItem("Tools/Text Editor")]
    public static void ShowWindow()
    {
        GetWindow<TextEditorWindow>("Text Editor");
    }

    private void OnGUI()
    {
        GUILayout.Label("Select Text Components to Edit", EditorStyles.boldLabel);

        if (GUILayout.Button("Find Text Components"))
        {
            FindAllTextComponents();
        }

        if (textComponents.Count > 0 || uiLabelComponents.Count > 0)
        {
            int totalComponents = textComponents.Count + uiLabelComponents.Count;
            GUILayout.Label($"{totalComponents} Text components found.", EditorStyles.label);

            GUILayout.BeginHorizontal();
            GUILayout.Label("Select Text to Edit:", GUILayout.Width(150));
            string[] keysArray = uniqueTexts.Keys.ToArray(); // 获取键数组

            if (GUILayout.Button("↑", GUILayout.Width(30)))
            {
                selectedIndex = (selectedIndex - 1 + keysArray.Length) % keysArray.Length;
                selectedText = keysArray[selectedIndex];
            }

            selectedIndex = EditorGUILayout.Popup(selectedIndex, keysArray); // 使用 selectedIndex 作为选中的索引

            if (GUILayout.Button("↓", GUILayout.Width(30)))
            {
                selectedIndex = (selectedIndex + 1) % keysArray.Length;
                selectedText = keysArray[selectedIndex];
            }

            GUILayout.EndHorizontal();

            if (!string.IsNullOrEmpty(selectedText))
            {
                newText = EditorGUILayout.TextField("New Text:", newText);

                if (GUILayout.Button("Update All Instances"))
                {
                    UpdateAllInstances();
                }
            }
        }
    }

    private void FindAllTextComponents()
    {
        textComponents.Clear();
        uiLabelComponents.Clear();
        uniqueTexts.Clear();

        // 查找所有游戏对象，包括隐藏的物体
        List<GameObject> allGameObjects = GetAllGameObjectsIncludingDisabled();

        // 查找所有 Text 组件，包括隐藏的物体
        textComponents.AddRange(allGameObjects.Select(go => go.GetComponent<Text>()).Where(text => text != null));
        // 查找所有 UILabel 组件，包括隐藏的物体
        uiLabelComponents.AddRange(allGameObjects.Select(go => go.GetComponent<UILabel>()).Where(uiLabel => uiLabel != null));

        foreach (var text in textComponents)
        {
            AddTextToUniqueDict(text.text, text);
        }

        foreach (var uiLabel in uiLabelComponents)
        {
            AddTextToUniqueDict(uiLabel.text, uiLabel);
        }
    }

    private List<T> FindObjectsOfTypeIncludingDisabled<T>() where T : MonoBehaviour
    {
        List<T> components = new List<T>();
        foreach (var go in GetAllGameObjectsIncludingDisabled())
        {
            T component = go.GetComponent<T>();
            if (component != null)
            {
                components.Add(component);
            }
        }
        return components;
    }

    private List<GameObject> GetAllGameObjectsIncludingDisabled()
    {
        List<GameObject> allObjects = new List<GameObject>();

        // 获取所有根游戏对象
        foreach (var go in Object.FindObjectsOfType<GameObject>())
        {
            if (go.transform.parent == null)
            {
                GetAllGameObjectsIncludingDisabledRecursively(go.transform, allObjects);
            }
        }

        return allObjects;
    }

    private void GetAllGameObjectsIncludingDisabledRecursively(Transform parent, List<GameObject> allObjects)
    {
        // 添加当前父对象的游戏对象到列表中
        allObjects.Add(parent.gameObject);

        // 递归地遍历所有子对象
        for (int i = 0; i < parent.childCount; i++)
        {
            Transform child = parent.GetChild(i);
            GetAllGameObjectsIncludingDisabledRecursively(child, allObjects);
        }
    }

    private void AddTextToUniqueDict(string text, MonoBehaviour component)
    {
        if (!uniqueTexts.ContainsKey(text))
        {
            uniqueTexts[text] = new List<MonoBehaviour>();
        }
        uniqueTexts[text].Add(component);
    }

    private void UpdateAllInstances()
    {
        if (uniqueTexts.ContainsKey(selectedText))
        {
            foreach (var component in uniqueTexts[selectedText])
            {
                if (component is Text)
                {
                    ((Text)component).text = newText;
                }
                else if (component is UILabel)
                {
                    ((UILabel)component).text = newText;
                }

                EditorUtility.SetDirty(component);
            }

            EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
            EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene());
        }
    }
}
